<!-- HeaderBar.vue（整合上传下载） -->

<template>
  <div class="app-header">
    <!-- 左侧：Logo -->
    <div class="header-section left" @click="goHome" style="cursor: pointer">
      <div class="logo">📘 语雀文档</div>
    </div>

    <!-- 中间：搜索框 -->
    <div class="header-section center">
      <el-autocomplete
        v-model="search"
        :fetch-suggestions="fetchSearchResults"
        placeholder="搜索文档..."
        prefix-icon="Search"
        class="search-input"
        clearable
        popper-class="search-suggestions"
        @select="handleSelect"
      >
        <template #default="{ item }">
          <div class="search-item">
            <div class="search-title">{{ item.title }}</div>
            <div class="search-content" v-html="item.html"></div>
          </div>
        </template>
      </el-autocomplete>
    </div>

    <!-- 右侧：头像或登录注册 -->
    <div class="header-section right">
      <el-dropdown trigger="hover" @command="handleCommand" class="avatar-dropdown">
        <span class="avatar-wrapper">
          <el-avatar :src="user.avatar || ''" icon="User" class="hover-avatar" />
        </span>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item disabled class="username-display">
              👤 {{ user.username }}
            </el-dropdown-item>
            <el-dropdown-item command="profile">个人中心</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import { useUserStore } from '@/stores/userStore'
import service from '@/utils/request'

const router = useRouter()
const search = ref('')
const userStore = useUserStore()

const user = ref({})

function goHome() {
  router.push('/')
}

// 获取搜索建议
const fetchSearchResults = async (query, cb) => {
  if (!query.trim()) return cb([])
  try {
    const res = await service.get('/search', {
      params: { keyword: query },
    })

    // 假设每条记录为 { id, html }
    const suggestions = res.data.map((item) => ({
      value: item.docId,
      title: item.title,
      html: item.content,
    }))

    cb(suggestions)
  } catch (err) {
    console.error('搜索失败', err)
    cb([])
  }
}

// 点击搜索建议项
const handleSelect = (item) => {
  router.push(`/docs/view/${item.value}`)
  search.value = ''
}

function handleCommand(command) {
  if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'logout') {
    localStorage.removeItem('token')
    useUserStore().logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  }
}

onBeforeMount(() => {
  user.value = userStore.getUserInfo()
})
</script>

<style scoped>
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  width: 100%;
}

.header-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.left {
  justify-content: flex-start;
}

.center {
  justify-content: center;
}

.right {
  justify-content: flex-end;
  gap: 16px;
}

.logo {
  font-size: 18px;
  font-weight: bold;
  margin-right: 24px;
  color: #333;
}

.search-input {
  flex: 1;
  max-width: 400px;
  margin-right: auto;
}

/* 自定义搜索下拉样式 */
::v-deep(.search-suggestions .el-autocomplete-suggestion__list li) {
  white-space: normal;
  padding: 8px 12px;
  line-height: 1.4;
}

/* 渲染搜索结果为 HTML */
::v-deep(.el-autocomplete-suggestion__wrap li) {
  display: block;
}

/* 允许插入的 HTML 生效 */
::v-deep(.el-autocomplete-suggestion__list li div) {
  font-size: 14px;
  color: #333;
}

.avatar-wrapper {
  display: inline-flex;
  align-items: center;
  outline: none;
  border: none;
}

.hover-avatar {
  transition: transform 0.2s ease;
}

.avatar-dropdown:hover .hover-avatar {
  transform: scale(1.2);
}

/* 显示用户名的项样式 */
.username-display {
  font-weight: bold;
  color: #666;
  cursor: default;
  pointer-events: none;
}

.search-suggestions .search-item {
  padding: 8px;
  line-height: 1.4;
}
.search-suggestions .search-title {
  font-weight: bold;
  color: #333;
}
.search-suggestions .search-content {
  color: #666;
  font-size: 13px;
}
</style>
